class Solution:
    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> list:
        up, down, left, right = (-1, 0), (1, 0), (0, -1), (0, 1)
        state = {right: down, down: left, left: up, up: right}
        res = []
        d = right
        x, y = rStart, cStart
        n = 0
        while len(res) < rows * cols:
            for _ in range(n//2+1):
                if x >= 0 and x < rows and y >= 0 and y < cols:
                    res.append([x, y])
                x += d[0]
                y += d[1]
            n += 1
            d = state[d]

        return res
